#   Copyright (c)  鱼肠的渔场小组  2025-2025 . All rights reserved.
#   TradingPlatform_Server is licensed under Mulan PSL v2.
#   You can use this software according to the terms and conditions of the Mulan
#   PSL v2.
#   You may obtain a copy of Mulan PSL v2 at:
#            http://license.coscl.org.cn/MulanPSL2
#   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
#   KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
#   NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#   See the Mulan PSL v2 for more details.
import json
import logging
import os
import uuid

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password, check_password
from django.db import IntegrityError

from Server.enum import (
    CommonSuccessCode,
    CommonErrorCode, TakeoutBackCode, TakeoutState, StoreState, DiscussBackCode, AuditBackCode,
    UserBackCode, StoreBackCode, PaymentBackCode, OrderBackCode, OrderState, MenuBackCode, AddressBackCode,
    MessageBackCode
)
from Server.forms import RegisterForm, LoginForm
from Server.models import User, Takeout, Store, Discuss, Address, Kind, Message, Order, Payment, Menu

logger = logging.getLogger(__name__)

"""
---------------------------------------------------------用户信息系统API接口-----------------------------------------------------------
"""


@csrf_exempt
def check_user(request):
    if request.method == "GET":
        phone = request.GET.get("phone")
        if not phone:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                User.objects.get(phone=phone)
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "获取用户信息成功",
                        "data": ''
                    }
                )
            except User.DoesNotExist:
                return JsonResponse(
                    {
                        "code": UserBackCode.user_not_found.value,
                        "error": "用户不存在"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def user(request):
    """
     用户注册、基本信息更新、用户注销、获取当前用户信息
    :param request:
    :return: JsonResponse
    """
    if request.method == "POST":
        form = RegisterForm(request.POST or None)
        if form.is_valid():
            phone = form.cleaned_data["phone"]
            password = form.cleaned_data["password"]
            username = form.cleaned_data["username"]
            uid = form.cleaned_data["id"]
            if not phone or not username or not password or not uid:
                return JsonResponse(
                    {
                        "code": CommonErrorCode.param_not_found.value,
                        "error": "必要参数缺失或者为空"
                    }
                )
            else:
                logger.info("{} request register".format(phone))
                try:
                    User.objects.get(id=uid)
                    return JsonResponse(
                        {
                            "code": UserBackCode.registered_user.value,
                            "error": "用户已被注册"
                        }
                    )
                except User.DoesNotExist:
                    new_user = User(username=username, password=make_password(password), id=uid, phone=phone)
                    try:
                        new_user.save()
                    except IntegrityError:
                        return JsonResponse(
                            {
                                "code": UserBackCode.registered_user.value,
                                "error": "手机号已被注册"
                            }
                        )
                    logger.info("Success create user, user id is {}".format(uid))
                    back_user = {
                        'id': new_user.id,
                        'phone': new_user.phone,
                        'username': new_user.username,
                        'head_portrait': new_user.head_portrait.url,
                        'money': new_user.money,
                        'is_admin': new_user.is_admin
                    }
                    return JsonResponse(
                        {
                            "code": CommonSuccessCode.success.value,
                            "msg": "注册用户成功",
                            "data": back_user
                        }
                    )
        else:
            return JsonResponse(
                {
                    "code": CommonErrorCode.form_not_valid.value,
                    "error": "表单校验不通过"
                }
            )
    elif request.method in ("PUT", "UPDATE"):
        data = json.loads(request.body)
        # 用户信息更新
        user_id = data.get("id")
        new_username = data.get("username")
        new_phone = data.get("phone")

        # if not user_id:
        #     return JsonResponse({"code": 400, "msg": "缺少用户ID", "data": ""})

        user_one = User.objects.filter(id=user_id).first()
        if user_one:
            if new_username:
                user_one.username = new_username
            if new_phone and len(new_phone) == 11:
                user_one.phone = new_phone
            user_one.save()
            return JsonResponse({"code": CommonSuccessCode.success.value, "msg": "用户信息更新成功", "data": ""})
        # else:
        #     return JsonResponse({"code": CommonErrorCode.method_error.value, "msg": "找不到指定的用户", "data": ""})


    elif request.method == "DELETE":
        data = json.loads(request.body)
        # 用户信息注销
        user_id = data.get("id")

        # if not user_id:
        #     return JsonResponse({"code": 400, "msg": "缺少用户ID", "data": ""})

        user_one = User.objects.filter(id=user_id).first()
        if user_one:
            user_one.delete()
            return JsonResponse({"code": CommonSuccessCode.success.value, "msg": "用户注销成功", "data": ""})
        # else:
        #     return JsonResponse({"code": 404, "msg": "找不到指定的用户", "data": ""})

    elif request.method == "GET":
        uid = request.GET.get("id")
        logger.info('Request user by {}'.format(uid))
        if not uid:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                user_one = User.objects.get(id=uid)
                back_user = {
                    'id': user_one.id,
                    'phone': user_one.phone,
                    'username': user_one.username,
                    'head_portrait': user_one.head_portrait.url,
                    'money': user_one.money,
                    'is_admin': user_one.is_admin,
                    'password': user_one.password
                }
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "获取用户信息成功",
                        "data": back_user
                    }
                )
            except User.DoesNotExist:
                return JsonResponse(
                    {
                        "code": UserBackCode.user_not_found.value,
                        "error": "用户不存在"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def user_portrait_upload(request):
    """
    user_portrait_upload：用户头像上传接口
    :param request:
    :return:
    """
    if request.method == "POST":
        uid = request.GET.get("id")
        photo = request.FILES['file']
        if not uid or not photo:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            folder_path = os.path.exists(settings.MEDIA_ROOT + '/users/' + uid)
            if not folder_path:
                os.mkdir(settings.MEDIA_ROOT + '/users/' + uid)
            try:
                user_one = User.objects.get(id=uid)
                user_one.head_portrait = photo
                user_one.save()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        'msg': '图片上传成功',
                        "data": ""
                    }
                )
            except User.DoesNotExist:
                return JsonResponse(
                    {
                        "code": UserBackCode.user_not_found.value,
                        'error': '找不到指定的用户'
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def update_password(request):
    """
    修改密码
    :param request:
    :return: JsonResponse
    """
    if request.method in ("PUT", "UPDATE"):
        # 用户密码修改
        data = json.loads(request.body)
        user_id = data.get("id") or data.get("user_id")
        old_password = data.get("old_password")
        new_password = data.get("new_password")

        # if not (user_id and old_password and new_password):
        #     return JsonResponse({"code": 400, "msg": "缺少必要参数", "data": ""})

        user_one = User.objects.filter(id=user_id).first()
        if user_one:
            if check_password(old_password, user_one.password) or user_one.password == old_password:
                user_one.password = make_password(new_password)
                user_one.save()
                return JsonResponse({"code": CommonSuccessCode.success.value, "msg": "密码修改成功", "data": ""})
            else:
                return JsonResponse({"code": CommonErrorCode.form_not_valid.value, "error": "旧密码错误"})
        else:
            return JsonResponse({"code": UserBackCode.user_not_found.value, "error": "用户不存在"})
    else:
        return JsonResponse({"code": CommonErrorCode.method_error.value, "msg": "请求方式错误", "data": ""})


"""
---------------------------------------------------------外卖信息系统API接口-----------------------------------------------------------
"""


@csrf_exempt
def takeout_portrait_upload(request):
    """
    takeout_portrait_upload：外卖照片上传接口
    :param request: id、takeout
    :return: JsonResponse
    """
    if request.method == "POST":
        takeout_id = request.GET.get("id")
        photo = request.FILES['file']
        if not takeout_id or not photo:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            folder_path = os.path.join(settings.MEDIA_ROOT, 'takeouts', takeout_id)
            if not os.path.exists(folder_path):
                os.mkdir(settings.MEDIA_ROOT + '/takeouts/' + takeout_id)
            try:
                takeout_one = Takeout.objects.get(id=takeout_id)
                takeout_one.takeout_portrait = photo
                takeout_one.save()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        'msg': '图片上传成功',
                        "data": ""
                    }
                )
            except Takeout.DoesNotExist:
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_not_found.value,
                        'error': '找不到指定的外卖'
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def takeout(request):
    """
    takeout：外卖接口，包括外卖创建、单个查询、外卖删除（下架）、外卖信息更新
    :param request: takeout_id、takeout_name、introduce、classification、price、store_id
    :return: JsonResponse
    """
    if request.method == "GET":
        logger.info("Request to query one takeout ")
        takeout_id = request.GET.get("id")
        if not takeout_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                query_takeout = Takeout.objects.get(id=takeout_id)
                query_takeout.flow += 1
                query_takeout.save()
                logger.info("Query one takeout success")
                json_takeout = {
                    "id": query_takeout.id,
                    "state": query_takeout.state,
                    "takeout_name": query_takeout.takeout_name,
                    "introduce": query_takeout.introduce,
                    "takeout_portrait": query_takeout.takeout_portrait.url,
                    "create_time": query_takeout.create_time,
                    "last_update_time": query_takeout.last_update_time,
                    "price": query_takeout.price,
                    "flow": query_takeout.flow,
                    "mark": query_takeout.mark,
                    "remark_count": query_takeout.remark_count,
                    "store": query_takeout.store_id,
                    "kind": query_takeout.kind_id
                }
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_takeout
                    }
                )
            except Takeout.DoesNotExist:
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_not_found.value,
                        "error": "找不到指定的外卖信息"
                    }
                )
    elif request.method == "POST":
        data = json.loads(request.body)
        logger.info("Request to create one takeout")
        takeout_name = data.get("takeout_name")
        introduce = data.get("introduce")
        kind_id = data.get("kind")
        price = data.get("price")
        store_id = data.get("store")
        if not takeout_name or not introduce or not kind_id or not price or not store_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            takeout_one = Takeout(takeout_name=takeout_name, introduce=introduce, kind_id=kind_id,
                                  price=price,
                                  store_id=store_id, state=TakeoutState.auditing.value)
            takeout_one.save()
            json_takeout = {
                "id": takeout_one.id,
                "state": takeout_one.state,
                "takeout_name": takeout_one.takeout_name,
                "introduce": takeout_one.introduce,
                "takeout_portrait": takeout_one.takeout_portrait.url,
                "create_time": takeout_one.create_time,
                "last_update_time": takeout_one.last_update_time,
                "price": takeout_one.price,
                "flow": takeout_one.flow,
                "mark": takeout_one.mark,
                "remark_count": takeout_one.remark_count,
                "store": takeout_one.store_id,
                "kind": takeout_one.kind_id
            }
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "外卖创建成功",
                    "data": json_takeout
                }
            )
    elif request.method == "DELETE":
        data = json.loads(request.body)
        logger.info("Request to delete one takeout")
        takeout_id = data.get("id")
        if not takeout_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                query_takeout = Takeout.objects.get(id=takeout_id)
                logger.info("Query one takeout success")
                query_takeout.delete()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "删除外卖成功",
                        "data": ""
                    }
                )
            except Takeout.DoesNotExist:
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_not_found.value,
                        "error": "找不到要删除的外卖"
                    }
                )
    elif request.method == "UPDATE":
        data = json.loads(request.body)
        logger.info("Request to update one takeout")
        takeout_id = data.get("id")
        takeout_name = data.get("takeout_name")
        introduce = data.get("introduce")
        price = data.get("price")
        if not takeout_name or not introduce or not price or not takeout_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                takeout_one = Takeout.objects.get(id=takeout_id)
                takeout_one.introduce = introduce
                takeout_one.price = price
                takeout_one.takeout_name = takeout_name
                takeout_one.save()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "外卖信息更新成功",
                        "data": ""
                    }
                )
            except Takeout.DoesNotExist:
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_not_found.value,
                        "error": "找不到要待更新信息的外卖"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_new_takeout(request):
    """
    query_recommend_takeout
    :param request:
    :return:
    """
    if request.method == "GET":
        takeout_list = Takeout.objects.filter(state=TakeoutState.audited.value).order_by('-create_time')[:10]
        if takeout_list.exists():
            json_takeout_list = [
                {
                    "id": item.id,
                    "state": item.state,
                    "takeout_name": item.takeout_name,
                    "introduce": item.introduce,
                    "takeout_portrait": item.takeout_portrait.url,
                    "create_time": item.create_time,
                    "last_update_time": item.last_update_time,
                    "price": item.price,
                    "flow": item.flow,
                    "mark": item.mark,
                    "remark_count": item.remark_count,
                    "store": item.store_id,
                    "kind": item.kind_id
                }
                for item in takeout_list
            ]
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "查询成功",
                    "data": json_takeout_list
                }
            )
        else:
            return JsonResponse(
                {
                    "code": TakeoutBackCode.takeout_list_empty.value,
                    "error": "查询外卖信息列表为空"
                }
            )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_recommend_takeout(request):
    """
    query_recommend_takeout
    :param request:
    :return:
    """
    if request.method == "GET":
        takeout_list = Takeout.objects.filter(state=TakeoutState.audited.value).order_by('-flow')[:5]
        if takeout_list.exists():
            json_takeout_list = [
                {
                    "id": item.id,
                    "state": item.state,
                    "takeout_name": item.takeout_name,
                    "introduce": item.introduce,
                    "takeout_portrait": item.takeout_portrait.url,
                    "create_time": item.create_time,
                    "last_update_time": item.last_update_time,
                    "price": item.price,
                    "flow": item.flow,
                    "mark": item.mark,
                    "remark_count": item.remark_count,
                    "store": item.store_id,
                    "kind": item.kind_id
                }
                for item in takeout_list
            ]
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "查询成功",
                    "data": json_takeout_list
                }
            )
        else:
            return JsonResponse(
                {
                    "code": TakeoutBackCode.takeout_list_empty.value,
                    "error": "查询外卖信息列表为空"
                }
            )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_store_takeout(request):
    """
    query_store_takeout
    :param request:
    :return:
    """
    if request.method == "GET":
        logger.info("Request to query class takeout by name")
        store_id = request.GET.get("id")
        if not store_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            takeout_list = Takeout.objects.filter(store_id=store_id, state=TakeoutState.audited.value)
            if takeout_list.exists():
                logger.info("Query store takeout list success")
                json_takeout_list = [
                    {
                        "id": item.id,
                        "state": item.state,
                        "takeout_name": item.takeout_name,
                        "introduce": item.introduce,
                        "takeout_portrait": item.takeout_portrait.url,
                        "create_time": item.create_time,
                        "last_update_time": item.last_update_time,
                        "price": item.price,
                        "flow": item.flow,
                        "mark": item.mark,
                        "remark_count": item.remark_count,
                        "store": item.store_id,
                        "kind": item.kind_id
                    }
                    for item in takeout_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_takeout_list
                    }
                )
            else:
                logger.info("Empty takeout list!")
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_list_empty.value,
                        "error": "查询外卖信息列表为空"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_name_takeout(request):
    """
    query_name_takeout
    :param request:
    :return:
    """
    if request.method == "GET":
        logger.info("Request to query class takeout by name")
        name = request.GET.get("takeout_name")
        if not name:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            takeout_list = Takeout.objects.filter(takeout_name__contains=name, state=TakeoutState.audited.value)
            if takeout_list.exists():
                logger.info("Query name takeout list success")
                json_takeout_list = [
                    {
                        "id": item.id,
                        "state": item.state,
                        "takeout_name": item.takeout_name,
                        "introduce": item.introduce,
                        "takeout_portrait": item.takeout_portrait.url,
                        "create_time": item.create_time,
                        "last_update_time": item.last_update_time,
                        "price": item.price,
                        "flow": item.flow,
                        "mark": item.mark,
                        "remark_count": item.remark_count,
                        "store": item.store_id,
                        "kind": item.kind_id
                    }
                    for item in takeout_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_takeout_list
                    }
                )
            else:
                logger.info("Empty takeout list!")
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_list_empty.value,
                        "error": "查询指定外卖信息列表为空"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_kind_takeout(request):
    """
    query_class_takeout
    :param request:
    :return:
    """
    if request.method == "GET":
        logger.info("Request to query class takeout by kind")
        kind_id = request.GET.get("kind")
        if not kind_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            takeout_list = Takeout.objects.filter(
                kind_id=kind_id, state=TakeoutState.audited.value
            )
            if takeout_list.exists():
                logger.info("Query kind takeout success")
                json_takeout_list = [
                    {
                        "id": item.id,
                        "state": item.state,
                        "takeout_name": item.takeout_name,
                        "introduce": item.introduce,
                        "takeout_portrait": item.takeout_portrait.url,
                        "create_time": item.create_time,
                        "last_update_time": item.last_update_time,
                        "price": item.price,
                        "flow": item.flow,
                        "mark": item.mark,
                        "remark_count": item.remark_count,
                        "store": item.store_id,
                        "kind": item.kind_id
                    }
                    for item in takeout_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_takeout_list
                    }
                )
            else:
                logger.info("Empty takeout list!")
                return JsonResponse(
                    {
                        "code": TakeoutBackCode.takeout_list_empty.value,
                        "error": "查询指定外卖信息列表为空"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_all_takeout(request):
    """
    query_all_takeout
    :param request:
    :return:
    """
    if request.method == "GET":
        logger.info("Request to query all takeout")
        takeout_list = Takeout.objects.filter(state=TakeoutState.audited.value)
        if takeout_list.exists():
            logger.info("Query all takeout success")
            json_takeout_list = [
                {
                    "id": item.id,
                    "state": item.state,
                    "takeout_name": item.takeout_name,
                    "introduce": item.introduce,
                    "takeout_portrait": item.takeout_portrait.url,
                    "create_time": item.create_time,
                    "last_update_time": item.last_update_time,
                    "price": item.price,
                    "flow": item.flow,
                    "mark": item.mark,
                    "remark_count": item.remark_count,
                    "store": item.store_id,
                    "kind": item.kind_id
                }
                for item in takeout_list
            ]
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "查询成功",
                    "data": json_takeout_list
                }
            )
        else:
            logger.info("None takeout!")
            return JsonResponse(
                {
                    "code": TakeoutBackCode.takeout_list_empty.value,
                    "error": "查询指定外卖信息列表为空"
                }
            )

    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------支付系统API接口--------------------------------------------------------------
"""


@csrf_exempt
def payment(request):
    """
    处理支付请求
    :param request: 包含 price, payment_order_id, user_id 的 POST 请求
    :return: JsonResponse
    """
    if request.method == "POST":
        data = json.loads(request.body)
        price = data.get("price")
        user_id = data.get("user")
        store_id = data.get("store")
        order_id = data.get("order")
        if not price or not user_id or not store_id or not order_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                user_one = User.objects.get(id=user_id)
                if user_one.money - price >= 0:
                    payment_new = Payment(price=price, user_id=user_id, store_id=store_id, order_id=order_id)
                    user_one.money -= price
                    user_one.save()
                    payment_new.save()
                    return JsonResponse(
                        {
                            "code": CommonSuccessCode.success.value,
                            "msg": "支付成功",
                            "data": ""
                        }
                    )
                else:
                    return JsonResponse(
                        {
                            "code": UserBackCode.not_sufficient_funds.value,
                            "error": "余额不足"
                        }
                    )
            except User.DoesNotExist:
                return JsonResponse(
                    {
                        "code": UserBackCode.user_not_found.value,
                        "error": "用户不存在"
                    }
                )
    elif request.method == "GET":
        user_id = request.GET.get("user")
        if not user_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            payment_list = Payment.objects.filter(user_id=user_id)
            if payment_list.exists():
                json_payment_list = [
                    {
                        "id": item.id,
                        "store": item.store_id,
                        "user": item.user_id,
                        "order": item.order_id,
                        "pay_time": item.pay_time,
                        "price": item.price
                    }
                    for item in payment_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "支付记录查询成功",
                        "data": json_payment_list
                    }
                )
            else:
                logger.info("Payment record not found")
                return JsonResponse(
                    {
                        "code": PaymentBackCode.payment_list_empty.value,
                        "error": "支付记录列表为空"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def recharge(request):
    if request.method == "POST":
        data = json.loads(request.body)
        money = data.get("money")
        user_id = data.get("id")
        if not money or not user_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                user_one = User.objects.get(id=user_id)
                user_one.money += money
                user_one.save()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        'msg': '充值成功',
                        'data': ''
                    }
                )
            except User.DoesNotExist:
                return JsonResponse(
                    {
                        "code": UserBackCode.user_not_found.value,
                        "error": "用户不存在"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------订单系统API接口--------------------------------------------------------------
"""


@csrf_exempt
def order(request):
    """
    order：订单接口，包括生成当前订单、获取所有订单、取消当前订单、获取单个订单、签收订单
    :param request: order_id、price、count、payment_ment、note、store_id、address_id、user_id
    :return: JsonResponse
    """
    if request.method == "POST":
        data = json.loads(request.body)
        logger.info("Request to generate current order")
        count = data.get("count")
        payment_method = data.get("payment_method")
        note = data.get("note")
        price = data.get("price")
        store_id = data.get("store")
        address_id = data.get("address")
        user_id = data.get("user")
        takeout_id = data.get("takeout")
        if not count or not note or not price or not store_id or not address_id or not user_id or not takeout_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            order_id = uuid.uuid1()
            order_one = Order(order_id=order_id, user_id=user_id, store_id=store_id, count=count, price=price,
                              payment_method=payment_method, note=note, address_id=address_id,
                              state=OrderState.unfinished.value, takeout_id=takeout_id)
            order_one.save()
            json_order = {
                "id": order_one.id,
                "state": order_one.state,
                "price": order_one.price,
                "count": order_one.count,
                "create_time": order_one.create_time,
                "finish_time": order_one.finish_time,
                "note": order_one.note,
                "address": order_one.address_id,
                "payment_method": order_one.payment_method,
                "user": order_one.user_id,
                "store": order_one.store_id,
                "takeout": {
                    "id": order_one.takeout.id,
                    "state": order_one.takeout.state,
                    "takeout_name": order_one.takeout.takeout_name,
                    "introduce": order_one.takeout.introduce,
                    "takeout_portrait": order_one.takeout.takeout_portrait.url,
                    "create_time": order_one.takeout.create_time,
                    "last_update_time": order_one.takeout.last_update_time,
                    "price": order_one.takeout.price,
                    "flow": order_one.takeout.flow,
                    "mark": order_one.takeout.mark,
                    "remark_count": order_one.takeout.remark_count,
                    "store": order_one.takeout.store_id,
                    "kind": order_one.takeout.kind_id
                }
            }
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "订单生成成功",
                    "data": json_order
                }
            )
    elif request.method == "GET":
        user_id = request.GET.get("id")
        logger.info("Request to query all orders ")
        order_list = Order.objects.filter(user_id=user_id, state=OrderState.unfinished.value)
        if order_list.exists():
            logger.info("Query all orders success")
            json_order_list = [
                {
                    "id": item.id,
                    "state": item.state,
                    "price": item.price,
                    "count": item.count,
                    "create_time": item.create_time,
                    "finish_time": item.finish_time,
                    "note": item.note,
                    "address": item.address_id,
                    "payment_method": item.payment_method,
                    "user": item.user_id,
                    "store": {
                        "id": item.store.id,
                        "store_name": item.store.store_name,
                        "create_time": item.store.create_time,
                        "address": item.store.address,
                        "takeout_count": item.store.takeout_count,
                        "state": item.store.state,
                        "user": item.store.user_id,
                        "introduce": item.store.introduce
                    },
                    "takeout": {
                        "id": item.takeout.id,
                        "state": item.takeout.state,
                        "takeout_name": item.takeout.takeout_name,
                        "introduce": item.takeout.introduce,
                        "takeout_portrait": item.takeout.takeout_portrait.url,
                        "create_time": item.takeout.create_time,
                        "last_update_time": item.takeout.last_update_time,
                        "price": item.takeout.price,
                        "flow": item.takeout.flow,
                        "mark": item.takeout.mark,
                        "remark_count": item.takeout.remark_count,
                        "kind": {
                            "id": item.takeout.kind.id,
                            "type": item.takeout.kind.type,
                            "content": item.takeout.kind.content
                        }
                    }
                }
                for item in order_list
            ]
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "订单获取成功",
                    "data": json_order_list,
                }
            )
        else:
            logger.info("None order!")
            return JsonResponse(
                {
                    "code": OrderBackCode.order_list_empty.value,
                    "error": "订单列表为空"
                }
            )
    elif request.method == "DELETE":
        logger.info("Request to delete current order")
        order_id = request.GET.get("id")
        if not order_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                query_order = Takeout.objects.get(id=order_id)
                logger.info("Query one order success")
                query_order.delete()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "订单取消成功",
                        "data": ""
                    }
                )
            except Takeout.DoesNotExist:
                return JsonResponse(
                    {
                        "code": OrderBackCode.order_delete_failed.value,
                        "error": "订单不存在"
                    }
                )
    elif request.method == "PUT":
        data = json.loads(request.body)
        logger.info("Request to update one order")
        order_id = data.get("id")
        if not order_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空",
                }
            )
        else:
            try:
                order_one = Order.objects.get(id=order_id)
                order_one.state = OrderState.finished.value
                order_one.save()
                json_order = {
                    "id": order_one.id,
                    "state": order_one.state,
                    "price": order_one.price,
                    "count": order_one.count,
                    "create_time": order_one.create_time,
                    "finish_time": order_one.finish_time,
                    "note": order_one.note,
                    "address": order_one.address_id,
                    "payment_method": order_one.payment_method,
                    "user": order_one.user_id,
                    "store": order_one.store_id,
                    "takeout": {
                        "id": order_one.takeout.id,
                        "state": order_one.takeout.state,
                        "takeout_name": order_one.takeout.takeout_name,
                        "introduce": order_one.takeout.introduce,
                        "takeout_portrait": order_one.takeout.takeout_portrait.url,
                        "create_time": order_one.takeout.create_time,
                        "last_update_time": order_one.takeout.last_update_time,
                        "price": order_one.takeout.price,
                        "flow": order_one.takeout.flow,
                        "mark": order_one.takeout.mark,
                        "remark_count": order_one.takeout.remark_count,
                        "store": order_one.takeout.store_id,
                        "kind": order_one.takeout.kind_id
                    }
                }
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "订单更新成功",
                        "data": json_order
                    }
                )
            except Order.DoesNotExist:
                return JsonResponse(
                    {
                        "code": OrderBackCode.order_update_failed.value,
                        "error": "订单不存在"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_finished_order(request):
    if request.method == "GET":
        user_id = request.GET.get("id")
        logger.info("Request to query all orders ")
        order_list = Order.objects.filter(user_id=user_id, state=OrderState.finished.value)
        if order_list.exists():
            logger.info("Query all orders success")
            json_order_list = [
                {
                    "id": item.id,
                    "state": item.state,
                    "price": item.price,
                    "count": item.count,
                    "create_time": item.create_time,
                    "finish_time": item.finish_time,
                    "note": item.note,
                    "address": item.address_id,
                    "payment_method": item.payment_method,
                    "user": item.user_id,
                    "store": {
                        "id": item.store.id,
                        "store_name": item.store.store_name,
                        "create_time": item.store.create_time,
                        "address": item.store.address,
                        "takeout_count": item.store.takeout_count,
                        "state": item.store.state,
                        "user": item.store.user_id,
                        "introduce": item.store.introduce
                    },
                    "takeout": {
                        "id": item.takeout.id,
                        "state": item.takeout.state,
                        "takeout_name": item.takeout.takeout_name,
                        "introduce": item.takeout.introduce,
                        "takeout_portrait": item.takeout.takeout_portrait.url,
                        "create_time": item.takeout.create_time,
                        "last_update_time": item.takeout.last_update_time,
                        "price": item.takeout.price,
                        "flow": item.takeout.flow,
                        "mark": item.takeout.mark,
                        "remark_count": item.takeout.remark_count,
                        "kind": {
                            "id": item.takeout.kind.id,
                            "type": item.takeout.kind.type,
                            "content": item.takeout.kind.content
                        }
                    }
                }
                for item in order_list
            ]
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "订单获取成功",
                    "data": json_order_list,
                }
            )
        else:
            logger.info("None order!")
            return JsonResponse(
                {
                    "code": OrderBackCode.order_list_empty.value,
                    "error": "订单列表为空"
                }
            )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------配送信息系统API接口-----------------------------------------------------------
"""

"""
---------------------------------------------------------商家信息系统API接口-----------------------------------------------------------
"""


@csrf_exempt
def store(request):
    """
    store: 商家店铺接口
    :param request:
    :return: JsonResponse
    """
    if request.method == "POST":
        data = json.loads(request.body)
        user_id = data.get("user")
        store_name = data.get("store_name")
        new_address = data.get("address")
        introduce = data.get("introduce")
        if not store_name or not user_id or not new_address or not introduce:
            logger.warning("Invalid data for store application: {}".format(data))
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            store_id = uuid.uuid1()
            logger.info("Store application received for: {}, user_id: {}".format(store_name, user_id))
            new_store = Store(user_id=user_id, store_name=store_name, address=new_address, id=store_id,
                              introduce=introduce, state=StoreState.auditing.value)
            new_store.save()
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "店铺申请成功",
                    "data": str(store_id)
                }
            )
    elif request.method == "DELETE":
        data = json.loads(request.body)
        # 关闭店铺
        store_id = data.get("store_id")

        if store_id:
            logger.info("Store closure request for store id: {}".format(store_id))
            # 关闭店铺逻辑
            return JsonResponse(
                {"code": CommonSuccessCode.success.value, "msg": "店铺关闭成功", "store_id": store_id}
            )
        else:
            logger.warning("Store closure failed due to missing store_id")
            return JsonResponse(
                {"code": CommonErrorCode.method_error.value, "msg": "店铺关闭失败，缺少店铺ID"}
            )

    elif request.method == "UPDATE":
        data = json.loads(request.body)
        # 店铺信息修改
        store_id = data.get("store_id")
        new_store_name = data.get("new_store_name")
        logger.info("Store update request for store id: {}, new name: {}".format(store_id, new_store_name))
        # 检查 store_id 和 new_store_name 是否存在
        if store_id and new_store_name:
            # 获取店铺对象
            store_obj = Store.objects.filter(id=store_id).first()
            if store_obj:
                # 更新店铺信息
                store_obj.name = new_store_name
                store_obj.save()
                logger.info("Store updated successfully for store id: {}".format(store_id))
                return JsonResponse(
                    {"code": CommonSuccessCode.success.value, "msg": "店铺信息修改成功", "store_id": store_id}
                )
            else:
                logger.warning("Store update failed: store not found")
                return JsonResponse(
                    {"code": StoreBackCode.store_not_found.value, "msg": "未找到指定店铺"}
                )
        else:
            logger.warning("Store update failed due to missing parameters")
            return JsonResponse(
                {"code": CommonErrorCode.param_not_found.value, "msg": "店铺信息修改失败，缺少必要信息"}
            )

    elif request.method == "GET":
        user_id = request.GET.get("user")
        if not user_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            logger.info("Request to get store info for store_id: {}".format(user_id))
            try:
                store_info = Store.objects.get(user_id=user_id, state=StoreState.audited.value)
                json_store = {
                    "id": store_info.id,
                    "store_name": store_info.store_name,
                    "create_time": store_info.create_time,
                    "address": store_info.address,
                    "takeout_count": store_info.takeout_count,
                    "state": store_info.state,
                    "user": store_info.user_id,
                    "introduce": store_info.introduce
                }
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_store
                    }
                )
            except Store.DoesNotExist:
                return JsonResponse(
                    {
                        "code": AuditBackCode.audit_store_not_found.value,
                        "error": "找不到待审核的店铺"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def query_store(request):
    if request.method == "GET":
        store_id = request.GET.get("store")
        if not store_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                store_info = Store.objects.get(id=store_id, state=StoreState.audited.value)
                json_store = {
                    "id": store_info.id,
                    "store_name": store_info.store_name,
                    "create_time": store_info.create_time,
                    "address": store_info.address,
                    "takeout_count": store_info.takeout_count,
                    "state": store_info.state,
                    "user": store_info.user_id,
                    "introduce": store_info.introduce
                }
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_store
                    }
                )
            except Store.DoesNotExist:
                return JsonResponse(
                    {
                        "code": AuditBackCode.audit_store_not_found.value,
                        "error": "找不到待审核的店铺"
                    }
                )


"""
---------------------------------------------------------管理员系统API接口-------------------------------------------------------------
"""


def admin_auth(uid):
    """
    admin_auth
    """
    try:
        User.objects.get(id=uid, is_admin=True)
    except User.DoesNotExist:
        return JsonResponse(
            {
                "code": UserBackCode.not_admin_user.value,
                "error": "非法请求"
            }
        )


@csrf_exempt
def audit_takeout(request):
    """
    audit_store: 审核外卖
    :param request:
    :return: JsonResponse
    """
    if request.method == "POST":
        data = json.loads(request.body)
        logger.info("Request to audit takeout")
        uid = data.get("id")
        takeout_id = data.get("takeout_id")
        state = data.get("state")
        if not takeout_id or not state or not uid:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                admin_auth(uid=uid)
                takeout_one = Takeout.objects.get(id=takeout_id)
                if state == TakeoutState.audited.value:
                    takeout_one.state = TakeoutState.audited.value
                    takeout_one.save()
                    logger.info("Takeout audited")
                    takeout_message(takeout_id=takeout_one.id, is_pass=True)
                    return JsonResponse(
                        {
                            "code": CommonSuccessCode.success.value,
                            "msg": "审核通过",
                            "data": ""
                        }
                    )
                else:
                    takeout_one.state = TakeoutState.reject.value
                    takeout_one.save()
                    takeout_message(takeout_id=takeout_one.id, is_pass=False)
                    logger.info("Takeout rejected")
                    return JsonResponse(
                        {
                            "code": AuditBackCode.fail_the_audit.value,
                            "error": "审核不通过"
                        }
                    )
            except Takeout.DoesNotExist:
                return JsonResponse(
                    {
                        "code": AuditBackCode.audit_takeout_not_found.value,
                        "error": "找不到待审核的外卖"
                    }
                )
    elif request.method == "GET":
        uid = request.GET.get("id")
        logger.info("Request to query takeout which we want to audit")
        if not uid:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            admin_auth(uid=uid)
            takeout_list = Takeout.objects.filter(state=TakeoutState.auditing.value)
            if takeout_list.exists():
                json_takeout_list = [
                    {
                        "id": item.id,
                        "state": item.state,
                        "takeout_name": item.takeout_name,
                        "introduce": item.introduce,
                        "takeout_portrait": item.takeout_portrait.url,
                        "create_time": item.create_time,
                        "last_update_time": item.last_update_time,
                        "price": item.price,
                        "flow": item.flow,
                        "mark": item.mark,
                        "remark_count": item.remark_count,
                        "store": item.store_id,
                        "kind": item.kind_id
                    }
                    for item in takeout_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_takeout_list,
                    }
                )
            else:
                return JsonResponse(
                    {
                        "code": AuditBackCode.audit_takeout_list_empty.value,
                        "error": "待审核外卖列表为空"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def audit_store(request):
    """
    audit_store: 审核店铺
    :param request:
    :return: JsonResponse
    """
    if request.method == "POST":
        data = json.loads(request.body)
        logger.info("Request to audit takeout")
        uid = data.get("id")
        store_id = data.get("store_id")
        state = data.get("state")
        if not store_id or not state or not uid:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                admin_auth(uid=uid)
                store_auditing = Store.objects.get(id=store_id)
                if state == StoreState.audited.value:
                    store_auditing.state = StoreState.audited.value
                    store_auditing.save()
                    store_message(store_id=store_auditing.id, is_pass=True)
                    logger.info("Store audited")
                    return JsonResponse(
                        {
                            "code": CommonSuccessCode.success.value,
                            "msg": "审核通过",
                            "data": ""
                        }
                    )
                else:
                    store_auditing.state = StoreState.reject.value
                    store_auditing.save()
                    store_message(store_id=store_auditing.id, is_pass=False)
                    logger.info("Store rejected")
                    return JsonResponse(
                        {
                            "code": AuditBackCode.fail_the_audit.value,
                            "error": "审核不通过"
                        }
                    )
            except Store.DoesNotExist:
                return JsonResponse(
                    {
                        "code": AuditBackCode.audit_store_not_found.value,
                        "error": "找不到待审核的店铺"
                    }
                )
    elif request.method == "GET":
        uid = request.GET.get("id")
        logger.info("Request to query store which we want to audit")
        if not uid:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            admin_auth(uid=uid)
            store_list = Store.objects.filter(state=StoreState.auditing.value)
            if store_list.exists():
                json_store_list = [
                    {
                        "id": item.id,
                        "store_name": item.store_name,
                        "create_time": item.create_time,
                        "address": item.address,
                        "takeout_count": item.takeout_count,
                        "state": item.state,
                        "user": item.user_id,
                        "introduce": item.introduce
                    }
                    for item in store_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_store_list
                    }
                )
            else:
                return JsonResponse(
                    {
                        "code": AuditBackCode.audit_store_list_empty.value,
                        "error": "待审核店铺列表为空"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------地址管理系统API接口------------------------------------------------------------
"""


@csrf_exempt
def address(request):
    """
    address_manager 获取地址
    :param request:
    :return: JsonResponse
    """
    if request.method == "GET":
        # 处理 GET 请求，查询所有地址
        logger.info("Query all addresses")
        user_id = request.GET.get("id")  # 从请求中获取用户ID
        if not user_id:
            # 如果用户ID缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            # 查询与用户ID对应的地址
            address_list = Address.objects.filter(user_id=user_id, state=False)
            if len(address_list) != 0:
                # 如果找到地址，构造返回结构
                back_address = [
                    {
                        "id": item.id,
                        'school_name': item.school_name,
                        'campus': item.campus,
                        'address': item.address,
                        'state': item.state
                    }
                    for item in address_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": back_address,
                    }
                )
            else:
                # 如果未找到地址，返回相应的错误信息
                return JsonResponse(
                    {
                        "code": AddressBackCode.address_not_found.value,
                        "error": "当前用户地址列表为空"
                    }
                )
    elif request.method == "POST":
        # 处理 POST 请求，添加新地址
        data = json.loads(request.body)  # 解析请求体中的JSON数据
        logger.info("Request to add new address")
        user_id = data.get("user")
        school_name = data.get("school_name")
        campus = data.get("campus")
        address = data.get("address")
        if not user_id or not school_name or not campus or not address:
            # 检查必填参数是否缺失
            return JsonResponse(
                {
                    "code": CommonErrorCode.method_error.value,
                    "msg": "必要参数缺失或者为空",
                    "data": ""
                }
            )
        else:
            # 创建新地址并保存到数据库
            new_address = Address(user_id=user_id, school_name=school_name, campus=campus, address=address)
            new_address.save()
            back_address = {
                'id': new_address.id,
                'school_name': new_address.school_name,
                'campus': new_address.campus,
                'address': new_address.address,
                'state': new_address.state
            }
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "地址添加成功",
                    "data": back_address
                }
            )
    elif request.method == "DELETE":
        # 处理 DELETE 请求，删除地址
        logger.info("Request to delete address")
        address_id = request.GET.get("id")  # 从请求中获取地址ID
        if not address_id:
            # 如果地址ID缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                # 尝试查找并删除指定的地址
                address_to_delete = Address.objects.get(id=address_id)
                address_to_delete.delete()
                logger.info("Address deleted")
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "成功删除地址",
                        "data": ""
                    }
                )
            except Address.DoesNotExist:
                # 如果地址不存在，返回相应的错误信息
                logger.info("Address not found")
                return JsonResponse(
                    {
                        "code": CommonErrorCode.address_not_found.value,
                        "error": "删除地址失败"
                    }
                )
    elif request.method == "PUT":
        # 处理 PUT 请求，更新地址
        data = json.loads(request.body)  # 解析请求体中的JSON数据
        logger.info("Request to update address")
        address_id = data.get("id")  # 从请求中获取地址ID
        user_id = data.get("user")
        if not address_id or not user_id:
            # 如果地址ID缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.method_error.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                # 将当前默认地址的状态设为False
                temp_address_list = Address.objects.filter(user_id=user_id, state=True)
                for item in temp_address_list:
                    item.state = False
                    item.save()
                try:
                    # 尝试查找并更新指定的地址
                    update_address = Address.objects.get(id=address_id)
                    update_address.state = True
                    update_address.save()
                    logger.info("Address updated")
                    return JsonResponse(
                        {
                            "code": CommonSuccessCode.success.value,
                            "msg": "地址更新成功",
                            "data": ''
                        }
                    )
                except Address.DoesNotExist:
                    # 如果地址不存在，返回相应的错误信息
                    return JsonResponse(
                        {
                            "code": AddressBackCode.address_not_found.value,  # 待修改
                            "error": "查找不到指定地址"
                        }
                    )
            except Address.DoesNotExist:
                # 如果没有默认地址，直接将指定地址设为默认
                update_address = Address.objects.get(id=address_id)
                update_address.state = True
                update_address.save()
                logger.info("Address updated")
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "地址更新成功",
                        "data": ''
                    }
                )
    else:
        # 如果请求方法不支持，返回错误信息
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "msg": "请求方式错误",
            }
        )


@csrf_exempt
def query_default_address(request):
    """
    quer_default_address 查询用户默认地址
    :param request: HTTP请求对象
    :return: JsonResponse 返回操作结果的JSON响应
    """
    if request.method == "GET":
        # 处理 GET 请求，查询默认地址
        user_id = request.GET.get("user")  # 从请求中获取用户ID
        if not user_id:
            # 如果用户ID缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.method_error.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                # 查找用户的默认地址
                default_address = Address.objects.get(user_id=user_id, state=True)
                back_address = {
                    'id': default_address.id,
                    'school_name': default_address.school_name,
                    'campus': default_address.campus,
                    'address': default_address.address,
                    'state': default_address.state
                }
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询默认地址成功",
                        "data": back_address
                    }
                )
            except Address.DoesNotExist:
                # 如果未找到默认地址，返回相应的错误信息
                return JsonResponse(
                    {
                        "code": AddressBackCode.default_address_not_found.value,
                        "error": "不存在默认地址"
                    }
                )
    else:
        # 如果请求方法不支持，返回错误信息
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "msg": "请求方式错误",
            }
        )


"""
---------------------------------------------------------评论系统API接口----------------------------------------------------------------
"""


@csrf_exempt
def discuss(request):
    """
    query_all_discuss 获取外卖所有评论
    :param request:
    :return: JsonResponse
    """
    if request.method == "GET":
        # 处理 GET 请求，查询默认地址
        logger.info("Query all discuss")
        takeout_id = request.GET.get("id")  # 从请求中获取外卖ID
        if not takeout_id:
            # 如果外卖ID缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            # 根据外卖ID查询评论
            discuss_list = Discuss.objects.filter(takeout_id=takeout_id)
            if discuss_list.exists():
                # 如果评论存在，构建JSON格式的评论列表
                json_discuss_list = [
                    {
                        "id": item.id,
                        "create_time": item.create_time,
                        "content": item.content,
                        "user": {
                            'id': item.user.id,
                            'username': item.user.username,
                            'head_portrait': item.user.head_portrait.url,
                        },
                        "takeout": {
                            "id": item.takeout.id,
                            "state": item.takeout.state,
                            "takeout_name": item.takeout.takeout_name,
                            "introduce": item.takeout.introduce,
                            "takeout_portrait": item.takeout.takeout_portrait.url,
                            "create_time": item.takeout.create_time,
                            "last_update_time": item.takeout.last_update_time,
                            "price": item.takeout.price,
                            "flow": item.takeout.flow,
                            "mark": item.takeout.mark,
                            "remark_count": item.takeout.remark_count,
                            "store": item.takeout.store_id,
                            "kind": item.takeout.kind_id
                        }
                    }
                    for item in discuss_list
                ]
                # 返回查询成功的结果
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "查询成功",
                        "data": json_discuss_list
                    }
                )
            else:
                # 如果评论列表为空，返回相应信息
                return JsonResponse(
                    {
                        "code": DiscussBackCode.discuss_not_found.value,
                        "error": "当前外卖评论列表为空"
                    }
                )
    elif request.method == "POST":
        # 处理 POST 请求，添加评论
        data = json.loads(request.body)  # 解析请求体中的JSON数据
        logger.info("Request to post discuss")
        content = data.get("content")  # 获取评论内容
        user_id = data.get("user")  # 获取用户ID
        takeout_id = data.get("takeout")  # 获取外卖ID
        if not content or not takeout_id or not user_id:
            # 如果必要参数缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            discuss_one = Discuss(content=content, user_id=user_id, takeout_id=takeout_id)
            takeout_one = Takeout.objects.get(id=takeout_id)
            takeout_one.remark_count += 1
            takeout_one.save()
            discuss_one.save()
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "评论成功",
                    "data": ""
                }
            )
    elif request.method == "DELETE":
        # 处理 DELETE 请求，删除评论
        data = json.loads(request.body)  # 解析请求体中的JSON数据
        logger.info("Request to delete discuss")
        discuss_id = data.get("discuss")  # 获取要删除评论的ID
        if not discuss_id:
            # 如果评论ID缺失，返回错误信息
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                # 尝试删除指定评论
                Discuss.objects.get(id=discuss_id).delete()
                logger.info("Discuss deleted")
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "成功删除评论",
                        "data": ""
                    }
                )
            except Discuss.DoesNotExist:
                # 如果评论不存在，返回相应信息
                logger.info("Not found discuss which we want to delete")
                return JsonResponse(
                    {
                        "code": DiscussBackCode.discuss_not_found.value,
                        "error": "当前评论不存在"
                    }
                )
    else:
        # 如果方法不支持，返回错误信息
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------菜单系统API接口----------------------------------------------------------------
"""


@csrf_exempt
def menu(request):
    """
    add_menu_item: 向菜单中添加菜品接口
    :param request: id（外卖唯一标识符）、count（数量）、price（价格）
    :return: JsonResponse
    """
    if request.method == 'POST':
        data = json.loads(request.body)
        user_id = data.get('user')
        count = data.get('count')
        price = data.get('price')
        takeout_id = data.get('takeout')
        if not count or not price or not takeout_id or not user_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            # 创建菜品条目
            new_menu_item = Menu(user_id=user_id, count=count, price=price, takeout_id=takeout_id)
            new_menu_item.save()
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "菜品添加成功",
                    "data": ""
                }
            )
    elif request.method == 'DELETE':
        menu_id = request.GET.get('id')
        user_id = request.GET.get('user')
        try:
            menu_one = Menu.objects.get(id=menu_id, user_id=user_id)
            menu_one.delete()
            logger.info(f"Menu item with menu_id {menu_id} deleted successfully")
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "删除成功",
                    "data": ""
                }
            )
        except Menu.DoesNotExist:
            logger.info("未找到删除目标")
            return JsonResponse(
                {
                    "code": MenuBackCode.menu_not_found.value,
                    "error": "找不到指定菜单"
                }
            )
    elif request.method == 'GET':
        user_id = request.GET.get('user')
        menu_items = Menu.objects.filter(user_id=user_id)
        if menu_items.exists():
            menu_list = [
                {
                    "id": item.id,
                    "create_time": item.create_time,
                    "count": item.count,
                    "price": item.price,
                    "user": {
                        "id": item.user.id,
                        "phone": item.user.phone
                    },
                    "takeout": {
                        "id": item.takeout.id,
                        "state": item.takeout.state,
                        "takeout_name": item.takeout.takeout_name,
                        "introduce": item.takeout.introduce,
                        "takeout_portrait": item.takeout.takeout_portrait.url,
                        "create_time": item.takeout.create_time,
                        "last_update_time": item.takeout.last_update_time,
                        "price": item.takeout.price,
                        "flow": item.takeout.flow,
                        "mark": item.takeout.mark,
                        "remark_count": item.takeout.remark_count,
                        "store": item.takeout.store_id,
                        "kind": item.takeout.kind_id
                    }
                }
                for item in menu_items
            ]
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "获取用户菜单成功",
                    "data": menu_list
                }
            )
        else:
            logger.info(f"No menu items found for user_id {user_id}")
            return JsonResponse(
                {
                    "code": MenuBackCode.menu_list_empty.value,
                    "error": "用户菜单列表为空"
                }
            )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------类型系统API接口----------------------------------------------------------------
"""


@csrf_exempt
def kind(request):
    if request.method == "GET":
        logger.info("Query all kind")
        kind_list = Kind.objects.all()
        json_kind = [
            {
                "id": item.id,
                "type": item.type,
                "content": item.content
            }
            for item in kind_list
        ]
        return JsonResponse(
            {
                "code": CommonSuccessCode.success.value,
                "msg": "查询成功",
                "data": json_kind
            }
        )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


@csrf_exempt
def single_kind(request):
    if request.method == "GET":
        kind_id = request.GET.get("id")
        try:
            kind_one = Kind.objects.get(id=kind_id)
            json_kind = {
                "id": kind_one.id,
                "type": kind_one.type,
                "content": kind_one.content
            }
            return JsonResponse(
                {
                    "code": CommonSuccessCode.success.value,
                    "msg": "查询成功",
                    "data": json_kind
                }
            )
        except Kind.DoesNotExist:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    'error': '找不到指定类型'
                }
            )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )


"""
---------------------------------------------------------消息系统API接口----------------------------------------------------------------
"""


def store_message(store_id, is_pass):
    user_store = Store.objects.get(id=store_id)
    if is_pass:
        message_send = Message(title="商铺审核通过通知", content="恭喜您，您的商铺审核申请通过啦！",
                               user_id=user_store.user_id)
    else:
        message_send = Message(title="商铺审核拒绝通知", content="很遗憾，您的商铺审核申请未能通过！",
                               user_id=user_store.user_id)
    message_send.save()


def takeout_message(takeout_id, is_pass):
    user_takeout = Takeout.objects.get(id=takeout_id)
    user_store = Store.objects.get(id=user_takeout.store_id)
    if is_pass:
        message_send = Message(title="外卖审核通过通知", content="恭喜您，您的外卖审核申请通过啦！",
                               user_id=user_store.user_id)
    else:
        message_send = Message(title="外卖审核拒绝通知", content="很遗憾，您的外卖审核申请未能通过！",
                               user_id=user_store.user_id)
    message_send.save()


@csrf_exempt
def message(request):
    if request.method == "GET":
        logger.info("Query all message")
        user_id = request.GET.get("id")
        if not user_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            message_list = Message.objects.filter(user_id=user_id, state=0)
            if message_list.exists():
                user_messages = [
                    {
                        "id": item.id,
                        "title": item.title,
                        "content": item.content,
                        "user": item.user_id,
                        "create_time": item.create_time,
                        "state": item.state
                    }
                    for item in message_list
                ]
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": '查询成功',
                        "data": user_messages
                    }
                )
            else:
                return JsonResponse(
                    {
                        "code": MessageBackCode.message_list_empty.value,
                        "error": "用户消息列表为空"
                    }
                )
    elif request.method == "POST":
        data = json.loads(request.body)
        logger.info("Request to update message")
        user_id = data.get("user")
        message_id = data.get("id")
        if not user_id or not message_id:
            return JsonResponse(
                {
                    "code": CommonErrorCode.param_not_found.value,
                    "error": "必要参数缺失或者为空"
                }
            )
        else:
            try:
                update_message = Message.objects.get(id=message_id, user_id=user_id)
                update_message.state = 1
                update_message.save()
                return JsonResponse(
                    {
                        "code": CommonSuccessCode.success.value,
                        "msg": "消息状态更新成功",
                        "data": ""
                    }
                )
            except Message.DoesNotExist:
                return JsonResponse(
                    {
                        "code": MessageBackCode.message_not_found.value,
                        "error": "找不到指定的消息"
                    }
                )
    else:
        return JsonResponse(
            {
                "code": CommonErrorCode.method_error.value,
                "error": "请求方式错误"
            }
        )
